package com.longrise.android.byjk.plugins.poster.posterdetail;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.event.PosterEvent;
import com.longrise.android.byjk.event.PosterShareResultEvent;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.picedu.auxiliary.CurrentViewPager;
import com.longrise.android.byjk.plugins.poster.bean.ImageBean;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.AccessCount;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.ImgList;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.QrBitmap;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.utils.PrintLog;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by godliness on 2017/9/23.
 * 海报详情 分享页面
 */
public class PosterDetailActivity extends BaseActivity2<PosterDetailPresenter> implements PosterDetailView, View.OnClickListener, ViewPager.OnPageChangeListener {

    public static final String TAG = "PosterDetailActivity";

    public static final String EXTRA_TAG_NAME = "tab_name";
    public static final String EXTRA_CURRENT_POSITION = "current_position";
    public static final String EXTRA_TAG_TYPE = "tab_type";

    private CurrentViewPager mViewPager;
    private TextView mTvProgress;
    private TextView mTvTabName;
    private ImageView mIvNext;
    private ImageView mIvPre;
    private ImageView mIvClose;
    private LinearLayout ll_left, ll_right;

    private View mLLWeChat;
    private View mLLWeChatMoments;
    private View mLLQQ;
    private View mLLQQZone;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private List<ImageBean> mImages = new ArrayList<>();
    private final StringBuilder mStr = new StringBuilder();

    private int mCurrentPosition = 0;
    private int mTotalSize;
    private String mCataName, type;
    private String id;

    @Override
    public int getContentViewId(@Nullable Bundle saveState) {
        if (saveState != null) {
            onRestoreState(saveState);
        } else {
            getExtraData();
        }
        return R.layout.activity_postershow;
    }

    /**
     * 需要当前索引位置、当前类别名
     */
    private void getExtraData() {
        Intent extraIntent = getIntent();
        mCataName = extraIntent.getStringExtra(EXTRA_TAG_NAME);
        type = extraIntent.getStringExtra(EXTRA_TAG_TYPE);
        mCurrentPosition = extraIntent.getIntExtra(EXTRA_CURRENT_POSITION, 0);
    }

    private void onRestoreState(Bundle state) {
        if (state != null) {
            mCataName = state.getString(EXTRA_TAG_NAME);
            mCurrentPosition = state.getInt(EXTRA_CURRENT_POSITION);
            type = state.getString(EXTRA_TAG_TYPE);
        }
    }

    @Override
    public void initView() {
        setToolbarVisible(false);
        mViewPager = (CurrentViewPager) findViewById(R.id.container);
        mTvProgress = (TextView) findViewById(R.id.tv_progress);
        mTvTabName = (TextView) findViewById(R.id.tv_tagname);
        mTvTabName.setText(mCataName);
        mIvNext = (ImageView) findViewById(R.id.iv_next);
        mIvPre = (ImageView) findViewById(R.id.iv_pre);
        mIvClose = (ImageView) findViewById(R.id.iv_cancle);
        ll_left = (LinearLayout) findViewById(R.id.ll_left);
        ll_right = (LinearLayout) findViewById(R.id.ll_right);
//        mPresenter.getData(type);
        initShareView();
        addAdapter();
        notifyDataInAdapter();
        setIconStatus();

        //获取二维码
//        getCodeImg();
        QrBitmap.getInstance().clearBitmap();
        QrBitmap.getInstance().createAndGetQrBitmap(mContext);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onToolbarBackClick() {

    }

    @Override
    public void initTheme() {
        setTheme(R.style.Transparent_AppCompatThem);
    }

    private void initShareView() {
        mLLWeChat = findViewById(R.id.shareapp_wechat_ll);
        mLLWeChatMoments = findViewById(R.id.shareapp_pengyouquan_ll);
        mLLQQ = findViewById(R.id.shareapp_qq_ll);
        mLLQQZone = findViewById(R.id.shareapp_qzone_ll);
        regEvent(true);
    }

    private void regEvent(boolean isClick) {
        if (mIvNext != null) {
            mIvNext.setOnClickListener(isClick ? this : null);
        }
        if (mIvPre != null) {
            mIvPre.setOnClickListener(isClick ? this : null);
        }
        if (mViewPager != null) {
            mViewPager.addOnPageChangeListener(isClick ? this : null);
        }
        if (mLLWeChat != null) {
            mLLWeChat.setOnClickListener(isClick ? this : null);
        }
        if (mLLWeChatMoments != null) {
            mLLWeChatMoments.setOnClickListener(isClick ? this : null);
        }
        if (mLLQQ != null) {
            mLLQQ.setOnClickListener(isClick ? this : null);
        }
        if (mLLQQZone != null) {
            mLLQQZone.setOnClickListener(isClick ? this : null);
        }
        if (mIvClose != null) {
            mIvClose.setOnClickListener(isClick ? this : null);
        }

        if (!isClick) {
            unRegEvent();
        }
    }

    private void unRegEvent() {
        EventBus.getDefault().unregister(this);
    }

    private void add() {
        mImages.clear();
        mImages = ImgList.getInstance().getImgs();
        if (mImages.size() != 0 && mCurrentPosition <= mImages.size()) {
            id = mImages.get(mCurrentPosition).getGoodsid();
            if (mCurrentPosition == 0) {
                AccessCount.getInstance().accessIn(id);
            }
        }
        mSectionsPagerAdapter.notifyDataSetChanged();
    }

    private void notifyDataInAdapter() {
        add();
        mTotalSize = mImages.size();
        setCurrentProgress();

        if (mViewPager != null) { //注意越界
            mViewPager.post(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(mCurrentPosition, true);
                }
            });
        }
    }

    /**
     * 设置分享是否允许enable 如果当前海报未加载完成之前不允许点击分享
     */
    private void setShareBtnEnable(boolean enable) {
        if (mLLWeChat != null) {
            mLLWeChat.setEnabled(enable);
        }
        if (mLLWeChatMoments != null) {
            mLLWeChatMoments.setEnabled(enable);
        }
        if (mLLQQ != null) {
            mLLQQ.setEnabled(enable);
        }
        if (mLLQQZone != null) {
            mLLQQZone.setEnabled(enable);
        }
    }


    private void addAdapter() {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    @Override
    public void showToast(String msg) {
        super.showToast(msg);
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_next:
                mPresenter.prev(mCurrentPosition);
                break;

            case R.id.iv_pre:
                mPresenter.next(mCurrentPosition, mTotalSize);
                break;

            case R.id.shareapp_wechat_ll:  //微信好友
                mPresenter.preformShare(2, id);
                break;

            case R.id.shareapp_pengyouquan_ll:  //朋友圈
                mPresenter.preformShare(3, id);

                break;
            case R.id.shareapp_qq_ll:  //QQ
                mPresenter.preformShare(4, id);
                break;

            case R.id.shareapp_qzone_ll:  //QQ空间
                mPresenter.preformShare(1, id);
                break;

            case R.id.iv_cancle:
                close();
                break;

            default:
        }
    }

    private int size() {
        return mImages == null ? 0 : mImages.size();
    }

    /**
     * 当前进度
     */
    private void setCurrentProgress() {
        if (mTvProgress != null) {
            mStr.setLength(0);
            mStr.append(mCurrentPosition + 1).append("/").append(mTotalSize);
            mTvProgress.setText(mStr.toString());
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCurrentPosition = position;
        id = mImages.get(position).getGoodsid();
        setIconStatus();
        setCurrentProgress();
        addAccessRecord();
    }

    private void setIconStatus() {
        PrintLog.e("setIconStatus", "mCurrentPosition = " + mCurrentPosition + " mTotalSize = " + mTotalSize);
        if (mCurrentPosition == 0) {
            mIvNext.setVisibility(View.GONE);
            ll_left.setVisibility(View.GONE);
            mIvPre.setVisibility(View.VISIBLE);
            ll_right.setVisibility(View.VISIBLE);
        } else if (mCurrentPosition == mTotalSize - 1) {
            mIvPre.setVisibility(View.GONE);
            ll_right.setVisibility(View.GONE);
            ll_left.setVisibility(View.VISIBLE);
            mIvNext.setVisibility(View.VISIBLE);
        } else {
            mIvPre.setVisibility(View.VISIBLE);
            mIvNext.setVisibility(View.VISIBLE);
            ll_left.setVisibility(View.VISIBLE);
            ll_right.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 当前海报累加一条访问记录
     */
    private void addAccessRecord() {
        AccessCount.getInstance().accessIn(id);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 创建一个新的Fragment
     */
    private PosterFragment newPosterInstance(int position) {
        String url = mImages.get(position).getDetailpicurl();
        Bundle bundle = new Bundle();
        bundle.putInt(PosterFragment.EXTRA_PARAMS_POSITION, position);
        bundle.putString(PosterFragment.EXTRA_PARAMS_URL, url);
        PosterFragment posterFragment = new PosterFragment();
        posterFragment.setArguments(bundle);
        return posterFragment;
    }

    @Override
    public void setCurrentPosition(int position) {
        if (mViewPager != null) {
            mViewPager.setCurrentItem(position, true);
            if (mSectionsPagerAdapter != null) {
                mSectionsPagerAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void actFinish(int shared, String id) {
        close();
        PosterShareResultEvent event = new PosterShareResultEvent();
        event.setShareRes(shared+"");
        EventBus.getDefault().post(event);
    }

    @Override
    public void finishGetImage(boolean isFinish) {

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return newPosterInstance(position);
        }

        @Override
        public int getCount() {
            return size();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(EXTRA_TAG_NAME, mCataName);
        outState.putInt(EXTRA_CURRENT_POSITION, mCurrentPosition);

        EntityBean bean = AccessCount.getInstance().getAccessBean();
        EntityBean bean1 = AccessCount.getInstance().getShareBean();
        mPresenter.updateReadStatus(bean);
        mPresenter.updateShareStatus(bean1);
    }

    @Override
    protected void onRestoreInstanceState(Bundle saveState) {
        super.onRestoreInstanceState(saveState);
        //恢复后，如果数据丢失则直接关闭 要考虑二级缓存
        if (mImages == null || mImages.size() <= 0) {
            close();
        }
    }

    private void close() {
        PosterShareResultEvent event = new PosterShareResultEvent();
        event.setClosePage(true);
        EventBus.getDefault().post(event);
        finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerPosterEvent(PosterEvent event) {
        //图片存本地后 然后分享
        if (event.getCreateSave() != null &&event.getCreateSave().mSaved) {
            PrintLog.e("PoseterDetailactivity","222222222222");
            PosterFragPresenter.CreateSave createSave = event.getCreateSave();
            String id = event.getId();
            int flag = event.getFlag();
            mPresenter.toShare(flag, id, createSave);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.setFinished();
        mSectionsPagerAdapter = null;
        EventBus.getDefault().unregister(this);
        regEvent(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
